;(function ( $, window, undefined ) {
	Core.use('swfupload', 'template', 'fancybox',
			 'JS:plugins/artZoom/artZoom.js', function(){
		uploadSetting = $.extend({
			file_size_limit : 20*1024,
			file_types : "*.jpg;*.jpeg;*.gif;*.png",
			file_types_description : "jpg, gif, png等图片文件",
			file_upload_limit : 99,
			
			// The event handler functions are defined in handlers.js
			swfupload_preload_handler 				: preLoad,
			swfupload_load_failed_handler 			: loadFailed,
			file_queued_handler 					: fileQueued,
			file_queue_error_handler 				: fileQueueError,
			file_dialog_complete_handler 			: fileDialogComplete,
			upload_start_handler 					: uploadStart,
			upload_progress_handler 				: uploadProgress,
			upload_error_handler 					: uploadError,
			upload_success_handler 					: uploadSuccess,
			upload_complete_handler 				: uploadComplete,
			queue_complete_handler 					: queueComplete,	// Queue plugin event
			
			button_width: 80,
			button_height: 28,
			button_cursor : SWFUpload.CURSOR.HAND,
			button_window_mode : 'transparent',
			button_image_url: Core.path('IMG:blank.gif'),
			flash_url : Core.path('JS:plugins/swfupload/swfupload.swf'),
			
			custom_settings:{
				progressTargetID : 'uploadQueue',
				uploadTipID : 'uploadTip',
				uploadID : 'uploadBtn',
				templateID : 'uploadQueuedTemplate'
			},
			debug: G.DEBUG
		}, uploadSetting);
		
		var uploader = new SWFUpload(uploadSetting);
		
		/**
		 * Event Handlers
		 * These are my custom event handlers to make my
		 * web application behave the way I went when SWFUpload
		 * completes different tasks.  These aren't part of the SWFUpload
		 * package.  They are part of my application.  Without these none
		 * of the actions SWFUpload makes will show up in my application.
		 */
		function preLoad() {
			if (!this.support.loading) {
				alert("您的flash版本必须升级到10.0及以上版本才能够使用文件上传功能");
				return false;
			}
			setUploadTip.apply(this);
			var uploadBtn = $('#' + this.customSettings.uploadID)
				progressTarget = $('#' + this.customSettings.progressTargetID);
			uploadBtn.click(function(){
				if(!uploadBtn.attr('disabled')){
					Core.Util.btnDisable(uploadBtn);
					progressTarget.closest('form').submit();
				}else{
					alert('please uplaod');
				}
			});
		}
		function loadFailed() {
			$('#' + this.customSetting.uploadTipID).html('<span style="color:red;">抱歉，上传工具加载失败，请刷新再试。</span>');
		}
		function fileQueued(file) {
			try {
				var progress = new FileProgress(file, this.customSettings);
				progress.setStatus("处理中...");
			} catch (ex) {
				this.debug(ex);
			}
		}

		function fileQueueError(file, errorCode, message) {
			try {
				if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
					//alert("你选择上传的文件过多，请重新选择上传。");
					alert("文件数量超过限制, " +  (message > 1 ? "你最多还可以上传" +  message + " 个文件" : "您不能再上传文件"));
					return;
				}

				var progress = new FileProgress(file, this.customSettings);
				progress.setError();

				switch (errorCode) {
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					progress.setStatus("文件超过大小限制");
					this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					progress.setStatus("不能上传空文件");
					this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					progress.setStatus("文件类型错误");
					this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					alert("文件数量超过限制, " +  (message > 1 ? "你最多还可以上传" +  message + " 个文件" : "您不能再上传文件"));
					break;
				default:
					if (file !== null) {
						progress.setStatus("未知错误");
					}
					this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				}
			} catch (ex) {
		        this.debug(ex);
		    }
		}

		function fileDialogComplete(numFilesSelected, numFilesQueued) {
			try {
				/* I want auto start the upload and I can do that here */
				this.startUpload();
			} catch (ex)  {
		        this.debug(ex);
			}
		}

		function uploadStart(file) {
			try {
				/* I don't want to do any file validation or anything,  I'll just update the UI and
				return true to indicate that the upload should start.
				It's important to update the UI here because in Linux no uploadProgress events are called. The best
				we can do is say we are uploading.
				 */
				var progress = new FileProgress(file, this.customSettings);
				//progress.setStatus("Uploading...");
				progress.setDelete(this);
			}
			catch (ex) {}
			
			return true;
		}

		function uploadProgress(file, bytesLoaded, bytesTotal) {
			try {
				var percent = Math.ceil((bytesLoaded / bytesTotal) * 100),
					progress = new FileProgress(file, this.customSettings);
				progress.setProgress(percent);
				//progress.setStatus("Uploading...");
			} catch (ex) {
				this.debug(ex);
			}
		}

		function uploadSuccess(file, serverData) {
			try {
				var progress = new FileProgress(file, this.customSettings);
				progress.setStatus("处理完毕.");
				progress.setData(serverData);
				progress.setComplete();
				setUploadTip.apply(this, null);
			} catch (ex) {
				this.debug(ex);
			}
		}

		function uploadError(file, errorCode, message) {
			try {
				var progress = new FileProgress(file, this.customSettings);
				progress.setError();

				switch (errorCode) {
				case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
					progress.setStatus("上传错误: " + message);
					this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
					progress.setStatus("配置错误");
					this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
					progress.setStatus("上传失败");
					this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.IO_ERROR:
					progress.setStatus("服务器错误");
					this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
					progress.setStatus("访问错误");
					this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
					progress.setStatus("超过上传数量限制");
					this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
					progress.setStatus("没有找到文件");
					this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
					progress.setStatus("文件验证错误，跳过上传");
					this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
					if (this.getStats().files_queued === 0) {
						if(this.customSettings.cancelButtonId){
							document.getElementById(this.customSettings.cancelButtonId).disabled = true;
						}
					}
					progress.setStatus("取消上传");
					progress.setCancelled(this);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
					progress.setStatus("上传停止");
					break;
				default:
					progress.setStatus("发生未知错误: " + error_code);
					this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				}
			} catch (ex) {
		        this.debug(ex);
		    }
		}

		function uploadComplete(file) {}
		
		function queueComplete(numFilesUploaded) {
			setUploadTip.apply(this);
		}
		
		//更新状态
		function  setUploadTip(uploader) {
			var limit = uploadSetting.file_upload_limit,
				hasLimit = $('#'+ this.customSettings.progressTargetID + ' .photo-status.success').length;
			if(!limit){
				return ;
			}

			if(hasLimit > 0){
				$('#uploadTip').html('已添加' + hasLimit + '张，最多还可以添加' + (limit - hasLimit) + '张');
			}else{
				$('#uploadTip').html('每次最多可以添加' + limit + '张图片');
			}

			$('#' + this.customSettings.uploadID).attr('disabled', !(hasLimit > 0));//提交按钮显示隐藏
		};
	
		// Constructor
		// file is a SWFUpload file object
		// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
		// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
		function FileProgress(file, customSettings) {
			this.fileProgressID = file.id;
			this.setting = customSettings;
			this.fileProgressWrapper = $('#' + this.fileProgressID);
			if (!this.fileProgressWrapper.length) {
				this.fileProgressWrapper = $(template(customSettings.templateID, {fileID : file.id}));
				var name = file.name.substring(0, file.name.lastIndexOf('.')); //图片名替换
				this.fileProgressWrapper.find('#name').val(name);
				$('#' + customSettings.progressTargetID).append(this.fileProgressWrapper);
			}
		}
		FileProgress.prototype.setProgress = function (percentage) {
			this.fileProgressWrapper.find('.progress .bar').width( percentage + '%');
		};
		FileProgress.prototype.setComplete = function () {
			this.fileProgressWrapper.find('.photo-status').addClass('success').fadeOut('slow');
		};
		FileProgress.prototype.setDelete = function (uploader) {
			var _this = this,
				removeBtn = this.fileProgressWrapper.find('#removeBtn')
			removeBtn.click(function(){
				if(confirm(removeBtn.attr('data-alert') || '确认删除?')){
					_this.setCancelled(uploader);
				}
			});
		};
		FileProgress.prototype.setError = function () {
			this.fileProgressWrapper.find('.progress').addClass('error');
		};
		FileProgress.prototype.setCancelled = function (uploader) {
			var _this = this;
			this.fileProgressWrapper.fadeOut(500, function() {
				uploader.cancelUpload(this.fileProgressID);

				//swfupload没有已上传文件删除功能.所以只能添加file_upload_limit方式hack...
				if(_this.fileProgressWrapper.find('.photo-status.success').length >0){
					uploader.setFileUploadLimit( uploader.settings.file_upload_limit - 0 + 1 );
				}

				_this.fileProgressWrapper.remove();
				setUploadTip.apply(uploader);
			});			
		};
		FileProgress.prototype.setStatus = function (status) {
			this.fileProgressWrapper.find('.photo-status .status').html(status);
		};
		FileProgress.prototype.setData = function (serverData) {
			var data = $.parseJSON(serverData);
			if(data.success){
				data = data.message;
				var	_this = this,
					form = this.fileProgressWrapper.find('[name]'),
					formRotate = this.fileProgressWrapper.find('#rotate'),
					formPath = this.fileProgressWrapper.find('#path'),
					formName = this.fileProgressWrapper.find('#name'),
					
					thumb = this.fileProgressWrapper.find('.thumbnail'),

					rotateValue = 0,
					rotateBtn = this.fileProgressWrapper.find('#rotateBtn'),
					zoomBtn = this.fileProgressWrapper.find('#zoomBtn'),
					removeBtn = this.fileProgressWrapper.find('#removeBtn'),
					rotateBtn = this.fileProgressWrapper.find('#rotateBtn');
					
				//缩略图显示
				thumb.attr('src', data.thumbUrl);
				//图片旋转
				thumb.data('rotate', 0);
				rotateBtn.click(function(){
					rotateValue += 90;
					rotateValue = rotateValue === 360 ? 0 : rotateValue;
					$.imgRotate(thumb[0], rotateValue);
					thumb.data('rotate', rotateValue);
					formRotate.val(rotateValue);
				});
				
				// 点击查看大图片
				zoomBtn.fancybox({
					live: false,
					type: 'image',
					href: data.url,
					title: function(){
						return formName.val();
					},
					beforeShow: function (){
						var rotateValue = thumb.data('rotate');
						if(!rotateValue){
							return ;
						}
						var zoomImg = this.wrap.find('.fancybox-image');
						if($.inArray(rotateValue, [90, 270]) >= 0){
							var width = this.width,
								height = this.height;
							this.width = height;
							this.height = width;
						}
						$.imgRotate(zoomImg[0], rotateValue);
					}
				});
				//填充图片地址
				formPath.val(data.path);
				//更新表单选项的name值, 并增加IE placeholder支持
				form.attr('name', function(){
					return this.name.replace('[', '[' + _this.fileProgressID + '][');
				});
			}else{
				this.setError();
				this.setStatus(data.message);
			}
			
		};
		
	});
})( jQuery, window);